import { LOTTERY_CONFIG, DEFAULT_LOTTERY_DATA } from "@/common/lottery-config";

export class LotteryManager {
  constructor(vm) {
    this.vm = vm;
    this.timers = new Map();
    this.countdownTimers = new Map();
  }

  // 检查是否需要开奖
  checkDrawTime(lotteryType, currentTime, targetTime) {
    const config = LOTTERY_CONFIG[lotteryType];
    const drawTime = config.defaultTime
      ? this.getDrawTime(targetTime, config.defaultTime)
      : this.getHKDrawTime(targetTime);

    return currentTime >= drawTime;
  }

  // 获取开奖时间
  getDrawTime(date, time) {
    const [hours, minutes, seconds] = time.split(":");
    const drawTime = new Date(date);
    drawTime.setHours(hours, minutes, seconds);
    return drawTime;
  }

  // 获取香港彩开奖时间
  getHKDrawTime(nextIssueDay) {
    const currentDate = new Date();
    return this.getDrawTime(
      `${currentDate.getFullYear()}-${
        currentDate.getMonth() + 1
      }-${nextIssueDay}`,
      "21:30:00"
    );
  }

  // 动态显示开奖号码
  async showDrawNumbers(lotteryType, numbers) {
    console.log("Starting to show numbers:", lotteryType, numbers);
    const config = LOTTERY_CONFIG[lotteryType];
    const numberArray = numbers.opencode.split(",");

    // 创建初始数据
    let currentData = {
      issue: numbers.issue|| numbers.expect,
      opencode: "正,在,进,行,搅,珠,中",
      zodiac: ", , , , , ,",
      openTime: numbers.openTime || numbers.opentime,
      wave: "#cccccc,#cccccc,#cccccc,#cccccc,#cccccc,#cccccc,#cccccc",
      info: "數據來源macaujc.com",
    };

    // 先设置初始状态
    this.vm[config.stateKey][0] = { ...currentData };

    // 分割初始字符串
    let defaultCodes = currentData.opencode.split(",");
    let zodiacCodes = currentData.zodiac.split(",");
    let waveCodes = currentData.wave.split(",");

    // 使用 for 循环和 await 来确保顺序执行
    for (let i = 0; i < numberArray.length; i++) {
      // 等待1秒
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 更新号码
      defaultCodes[i] = numberArray[i];
      currentData.opencode = defaultCodes.join(",");

      // 获取球信息并更新属性
      const ballInfo = this.vm.$store.getters.getBallInfo(numberArray[i]);
      if (ballInfo) {
        zodiacCodes[i] = `${ballInfo.zodiac}/${ballInfo.line8}`;
        waveCodes[i] = ballInfo.wave;
        currentData.zodiac = zodiacCodes.join(",");
        currentData.wave = waveCodes.join(",");
      }

      // 创建新的对象以触发响应式更新
      const updatedData = { ...currentData };

      // 使用 Vue.set 或直接赋值更新视图
      this.vm.$set(this.vm[config.stateKey], 0, updatedData);

      // 等待视图更新
      await this.vm.$nextTick();
    }
  }

  // 更新倒计时
  updateCountdown(lotteryType, targetTime) {
    const config = LOTTERY_CONFIG[lotteryType];
    const now = new Date();
    const target = new Date(targetTime);
    const diff = target - now;

    if (diff <= 0) {
      this.resetLotteryData(lotteryType);
      return true;
    }

    const countdown = this.calculateCountdown(diff);
    this.updateCountdownDisplay(lotteryType, countdown);
    return false;
  }

  // 重置彩票数据
  resetLotteryData(lotteryType) {
    const config = LOTTERY_CONFIG[lotteryType];
    this.vm[config.stateKey][0] = { ...DEFAULT_LOTTERY_DATA };
  }

  // 工具方法
  sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  // 启动倒计时
  startCountdown(type, callback) {
    if (this.countdownTimers.has(type)) {
      clearInterval(this.countdownTimers.get(type));
    }

    const config = LOTTERY_CONFIG[type];
    const timer = setInterval(async () => {
      const targetTime = this.getTargetTime(type);
      const now = new Date();
      const diff = targetTime - now;
      // console.log(diff, "diff");
      if (diff <= 0) {
        // 倒计时结束，开始轮询
        // 计算时分秒
        const countdown = this.calculateCountdown(diff);
        callback(countdown);
        clearInterval(timer);
        // this.startPolling(type);
        return;
      }

      // 计算时分秒
      const countdown = this.calculateCountdown(diff);
      callback(countdown);
    }, 1000);

    this.countdownTimers.set(type, timer);
  }

  // 计算倒计时
  calculateCountdown(diff) {
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    return { hours, minutes, seconds };
  }

  // 获取目标时间
  getTargetTime(type) {
    const config = LOTTERY_CONFIG[type];
    const now = new Date();
    let targetTime;

    try {
      if (type === "HK") {
        // 香港彩特殊处理
        const issueInfo = this.vm.issueInfo?.[config.key];
        if (!issueInfo?.drawTime) {
          // 如果没有drawTime，使用默认时间
          targetTime = new Date(now);
          targetTime.setHours(21, 30, 0);

          // 如果当前时间已过今天的开奖时间，则目标时间设为明天
          if (now > targetTime) {
            targetTime.setDate(targetTime.getDate() + 1);
          }
        } else {
          targetTime = new Date(issueInfo.drawTime);
        }
      } else {
        // 澳门彩处理
        targetTime = new Date(now);
        const [hours, minutes, seconds] = config.defaultTime.split(":");
        targetTime.setHours(hours, minutes, seconds);

        // 如果当前时间已过今天的开奖时间，则目标时间设为明天
        if (now > targetTime) {
          targetTime.setDate(targetTime.getDate() + 1);
        }
      }
    } catch (error) {
      console.error("Error in getTargetTime:", error);
      // 返回默认时间
      targetTime = new Date(now);
      targetTime.setHours(21, 30, 0);
      if (now > targetTime) {
        targetTime.setDate(targetTime.getDate() + 1);
      }
    }

    return targetTime;
  }

  // 清除所有定时器
  clearAllTimers() {
    this.timers.forEach((timer) => clearInterval(timer));
    this.countdownTimers.forEach((timer) => clearInterval(timer));
    this.timers.clear();
    this.countdownTimers.clear();
  }

  // 在 LotteryManager 类中添加一个统一处理 opencode 的方法
  getOpencode(data) {
    return data.opencode || data.openCode || data.OPENCODE || "";
  }
}
